#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

#include "cmd.h"

void read_and_cmp(char *path, char *expected)
{
	int fd = open(path , O_RDONLY);

	char buff[1024];
	int count = read(fd, buff, sizeof(buff));
	buff[count] = 0;

	close(fd);
	assert(strcmp(buff, expected) == 0);
}

// echo hello >test.out
void test_exec_cmd()
{
	unlink("test.out");

	pid_t pid = fork();
	if(pid == 0) {
		struct cmd cmd = {
			2, {"echo", "hello", NULL}, NULL, ">test.out"
		};
		exec_cmd(&cmd);
		exit(0);
	}
	wait(NULL);

	read_and_cmp("test.out", "hello\n");
}

// cat <test.in | sort | uniq | cat >test.out
void test_exec_pipe_cmd()
{
	unlink("test.out");

	pid_t pid = fork();
	if(pid == 0) {
		// echo 3\n1\n3\n2\n2\n3 >test.in
		struct cmd cmdv[4] = {
			[0] = {1, {"cat", NULL}, "<test.in", NULL},
			[1] = {1, {"sort", NULL}, NULL, NULL},
			[2] = {1, {"uniq", NULL}, NULL, NULL},
			[3] = {1, {"cat", NULL}, NULL, ">test.out"}
		};
		exec_pipe_cmd(4, cmdv);
		exit(0);
	}
	wait(NULL);

	read_and_cmp("test.out", "1\n2\n3\n");
}
